package com.elbis.business.controller;

import java.io.Serializable;
import java.util.List;
import java.util.Locale;

import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;

import org.apache.log4j.Logger;

import com.elbis.action.LocaleConstants;
import com.elbis.business.entity.locale.Language;

public class LanguageController implements Serializable {

	private static final long serialVersionUID = -7682494483665056974L;

	private static final Logger logger = Logger
			.getLogger(LanguageController.class);

	private List<Language> availableLanguages;

	private StaticValuesBean staticValues = null;

	private Language currentLocale;

	@PostConstruct
	public void init() {
		currentLocale = new Language();
		currentLocale.setCode(LocaleConstants.DEFAULT_LANGUAGE_CODE);
		currentLocale.setName(LocaleConstants.DEFAULT_LANGUAGE_NAME);
		availableLanguages = staticValues.getLanguages();
	}

	public List<Language> getAvailableLanguages() {
		return availableLanguages;
	}

	public void setLocale(Language newLocaleCode) {
		if (newLocaleCode != null) {
			FacesContext.getCurrentInstance().getViewRoot()
					.setLocale(Locale.forLanguageTag(newLocaleCode.getCode()));
		}
	}

	public void languageChanged(ValueChangeEvent e) {
		Language newLocaleCode = (Language) e.getNewValue();
		setLocale(newLocaleCode);
		if (logger.isInfoEnabled()) {
			logger.info("Language changed to " + newLocaleCode.getCode());
		}
	}

	public void setStaticValues(StaticValuesBean staticValues) {
		this.staticValues = staticValues;
	}

	public Language getCurrentLocale() {
		return currentLocale;
	}

	public void setCurrentLocale(Language currentLocale) {
		this.currentLocale = currentLocale;
	}

	public String getLocaleCode() {
		return currentLocale.getCode();
	}
}
